<script setup>
import {ref, onMounted} from 'vue';
import {getCategory, getGoodsPage, queryGoods, delGoods, editStatus} from '@/apis/goods.js';
import editGoodsPage from '@/views/goods/editGoods.vue'
import {Search} from "@element-plus/icons-vue";

const formData = ref({
  title: undefined,
  userName: undefined,
  categoryId: undefined,
  status: undefined,
  findGoods: undefined,
});

const rules = ref({
  title: [],
  userName: [],
  categoryId: [],
  status: [],
});

const total = ref(0);
const current = ref(1);
const size = ref(10);
const categoryOptions = ref([]);
const tableData = ref([]);
const drawer = ref(false);
const goodsMsg = ref({});

const statusOptions = ref([
  {label: '禁用', value: 0},
  {label: '正常', value: 1},
]);



const init = async () => {
  await findCategory();
  await findGoodsPage();
};
const findCategory = async () => {
  await getCategory().then((res) => {
    if (res.data.code === 1) {
      categoryOptions.value = res.data.data;
    } else {
      // Handle error
      ElMessage.error(res.data.msg || '分类信息获取失败');
    }
  }).catch((err) => {
    // Handle error
    ElMessage.error('请求出错了：' + err);
  });
}

const findGoodsPage = async () => {
  await getGoodsPage({current: current.value, size: size.value}).then((res) => {
    if (res.data.code === 1) {
      tableData.value = res.data.data.records;
      total.value = Number(res.data.data.total);
    } else {
      // Handle error
      ElMessage.error(res.data.msg || '查询失败');
    }
  }).catch((err) => {
    // Handle error
    ElMessage.error('请求出错了：' + err);
  });
}

const getCategoryName = (categoryId) => {
  const category = categoryOptions.value.find(item => item.id === categoryId);
  return category ? category.name : '未知分类';
};

const goodsQuery = () => {
  current.value = 1;
  findGoodsPage();
};

const findGoodsList = () => {
  queryGoods(formData.value).then((res) => {
    console.log("findgoods")
    console.log(res)
    if (res.data.code === 1) {
      console.log(res);
      total.value = res.data.data.total;
      tableData.value = res.data.data.records;
    } else {
      ElMessage.error(res.data.msg || '查询失败');
    }
  }).catch((err) => {
    ElMessage.error('请求出错了：' + err);
  });
};

const editStatusGoodsById = (id, status) => {
  console.log(id)
  console.log(status)
  status = status === 0 ? 1 : 0
  editStatus(id, status).then((res) => {
    if (res.data.code === 1) {
      console.log(res);
      // Handle success
      findGoodsPage();
    } else {
      // Handle error
      ElMessage.error(res.data.msg || '操作失败');
    }
  }).catch()
}

const delGoodsById = (id) => {
  ElMessageBox.confirm('此操作将删除该商品, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    delGoods(id).then((res) => {
      if (res.data.code === 1) {
        ElMessage.success('删除成功');
        findGoodsPage();
      } else {
        // Handle error
        ElMessage.error(res.msg || '删除失败');
      }
    }).catch((err) => {
      // Handle error
      ElMessage.error('请求出错了：' + err);
    });
  })
};

const closeDrawer = () => {
  drawer.value = false;
};

const handleClose = () => {
// 确认弹窗
  if (confirm('确认退出不保存？')) {
    closeDrawer()
  }
}

const editGoodsById = (row) => {
  drawer.value = true;
  goodsMsg.value = row;
  console.log("goodstc")
  console.log(row)
};

const goodsSizeChange = (val) => {
  size.value = val;
  init();
};

const currentChange = (val) => {
  current.value = val;
  findGoodsPage();
};

onMounted(() => {
  init();
});
</script>

<template>
  <div id="goods-app" class="dashboard-container">
    <div class="container">
      <div class="tableBar">
        <el-form ref="editUser" :inline="true" :model="formData" :rules="rules" label-position="left"
                 label-width="92px">
              <el-form-item label="商品标题：" label-width="84px" prop="title">
                <el-input v-model="formData.title" :style="{width: '100%'}" clearable
                          placeholder="请输入商品标题"></el-input>
              </el-form-item>
              <el-form-item label="商品分类：" label-width="84px" prop="categoryId">
                <el-select v-model="formData.categoryId" :style="{width: '100%'}" clearable placeholder="请选择商品分类">
                   <el-option
                     v-for="(item, index) in categoryOptions"
                     :key="item.id" 
                     :label="item.name" 
                     :value="item.id" 
                   ></el-option>
                 </el-select>
              </el-form-item>
              <el-form-item label="商品状态：" label-width="84px" prop="status">
                <el-select v-model="formData.status" :style="{width: '100%'}" clearable placeholder="请选择商品状态">
                  <el-option v-for="(item, index) in statusOptions" :key="index" :disabled="item.disabled" :label="item.label"
                             :value="item.value"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label-width="0" prop="findGoods">
                <el-button :icon="Search" type="primary" @click="findGoodsList"> 查询</el-button>
              </el-form-item>
        </el-form>
      </div>
      <el-table :data="tableData" class="tableBox" stripe>
        <el-table-column label="商品标题" prop="title"></el-table-column>
        <el-table-column label="价格" prop="price"></el-table-column>
        <el-table-column label="商品分类" prop="categoryId">
			 <template #default="scope">
			        {{ getCategoryName(scope.row.categoryId) }}
			      </template>
        </el-table-column>
        <el-table-column label="商品状态">
          <template #default="scope">{{ scope.row.status === 0 ? '下架' : '上架' }}</template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="180">
          <template #default="scope">
            <el-button class="blueBug" size="small" type="text" @click="editGoodsById(scope.row)">修改</el-button>
            <el-button class="blueBug" size="small" type="text"
                       @click="editStatusGoodsById(scope.row.id,scope.row.status)">
              {{ scope.row.status === 1 ? '下架' : '上架' }}
            </el-button>
            <el-button class="delBut" size="small" type="text"
                       @click="delGoodsById(scope.row.id)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination v-model:current-page="current" :total=total background class="pageList" layout="prev, pager, next"
                     @current-change="currentChange"/>
    </div>
    <el-drawer
        v-model=drawer
        :before-close="handleClose"
        :destroy-on-close=true
        :direction='trl'
        size="30%"
        title="修改商品信息"
    >
      <edit-goods-page :goodsMsg="goodsMsg" @closeDrawer='closeDrawer'></edit-goods-page>
    </el-drawer>
  </div>
</template>

<style scoped>
@import "@/styles/page.css";

#goods-app {
  width: 100%;
  height: 100%;
  padding: 20px;
}

.tableBox {
  width: 100%;
  height: 100%;
}

.tableBar {
  width: 100%;
  height: 100%;
  padding: 20px 40px;
}

.el-table__cell {
  padding: 16px 12px;
}

el-table-column {
  height: 50px;
}

.el-table .cell {
  box-sizing: border-box;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: normal;
  word-break: break-all;
  line-height: 23px;
  padding: 16px 12px;
}


</style>